﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace mklib.json
{
	/// <summary>
	/// 对象容器
	/// </summary>
	internal class JsonValueObject : IEnumerable, IJsonValue
	{
		internal JsonValueObject(int depth)
		{
			this._Depth = depth;
			this.data = new Dictionary<string, IJsonValue> ();
		}
		private readonly Dictionary<string, IJsonValue> data;
		internal IEnumerable<KeyValuePair<string, IJsonValue>> Data
		{
			get
			{
				return data;
			}
		}

		internal IJsonValue this[string key]
		{
			get
			{
				return this.data [key];
			}
			set
			{
				this.data [key] = value;
			}
		}

		#region IJsonValue implementation

		private readonly int _Depth;
		int IJsonValue.Depth
		{
			get
			{
				return _Depth;
			}
		}

		JsonValueType IJsonValue.Type
		{
			get
			{
				return JsonValueType.Object;
			}
		}

		object IJsonValue.ValueOf ()
		{
			Dictionary<string, object> dic = new Dictionary<string, object> ();
			foreach (string key in data.Keys) {
				dic [key] = data [key].ValueOf();
			}
			return dic;
		}

		void IJsonValue.Each(JsonEachMethod m)
		{
			IJsonValue val;
			foreach (string key in this.data.Keys) {
				val = this.data [key];
				switch (val.Type) {
				case JsonValueType.Array:
				case JsonValueType.Object:
					m (key, null, val.Type, _Depth);
					val.Each (m);
					break;
				default:
					m (key, val.ValueOf (), val.Type, val.Depth);
					break;
				}
			}
		}

		#endregion

		#region IEnumerable implementation

		IEnumerator IEnumerable.GetEnumerator ()
		{
			return this.data.GetEnumerator ();
		}

		#endregion
	}
}

